package com.cssw.fyzb.busi.api.user;


import com.cssw.fyzb.busi.service.im.ImService;
import com.cssw.fyzb.busi.service.user.UserService;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplelock.SimpleLock;
import com.ydn.simplelock.SimpleLockFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Function(description = "关注用户", parameters = {
        @Parameter(name = "userId", type = Type.Integer, description = "用户编号", required = true),
        @Parameter(name = "followUserId", type = Type.String, description = "关注用户标识", required = true),
        @Parameter(name = "type", type = Type.String, description = "类型（1-关注 2-取消关注）", required = true),
})
@Component
public class FollowUser implements Action {

    @Autowired
    private UserService userService;

    @Autowired
    private ImService imService;

    @Autowired
    private SimpleLockFactory simpleLockFactory;

    private static final Logger logger = LoggerFactory.getLogger(UpdateAvatar.class);

    @Override
    public Response execute(Request request) throws Exception {
        Long userId = request.getLong("userId");
        Long followUserId = request.getLong("followUserId");

        if (userId.toString().equals(followUserId.toString())){
            return Response.fail("不能关注自己");
        }

        SimpleLock userLock = simpleLockFactory.getLock("FOLLOW_" + userId);
        SimpleLock followLock = simpleLockFactory.getLock("FOLLOW_" + followUserId);
        try {
            userLock.acquire();
            followLock.acquire();

            if ("1".equals(request.getString("type"))) {
                userService.follow(userId, followUserId);
                imService.sendFocusMeMsg(userId, followUserId);
            } else {
                userService.cancelFollow(userId, followUserId);
            }
            return Response.success();
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("操作失败");
        } finally {
            try{
                userLock.release();
            } catch (Exception e){
                logger.error("", e);
            }
            try{
                followLock.release();
            } catch (Exception e){
                logger.error("", e);
            }
        }
    }
}
